package main

import (
	"encoding/json"
	"fmt"
	"github.com/Alex-zs/my_docker/container"
	"github.com/Alex-zs/my_docker/network"
	log "github.com/sirupsen/logrus"
	"io/ioutil"
	"os"
	"strconv"
	"syscall"
)

func stopContainer(containerName string) {
	containerInfo, err := container.GetContainerInfoByName(containerName)
	if err != nil {
		log.Errorf("get container %s info error %v", containerName, err)
		return
	}

	// signal term to kill the progress by pid
	pidInt, err := strconv.Atoi(containerInfo.Pid)
	if err != nil {
		log.Errorf("convert pid from string to int error %v", err)
		return
	}

	if err := syscall.Kill(pidInt, syscall.SIGTERM); err != nil {
		log.Errorf("stop container %s error %v", containerName, err)
		return
	}
	syscall.Kill(pidInt, syscall.SIGKILL)

	// release ip and delete iptables rules
	if containerInfo.NetworkName != "" {
		network.Init()
		network.Disconnect(containerInfo)
	}

	containerInfo.Status = container.STOP
	containerInfo.Pid = ""
	newContentBytes, err := json.Marshal(containerInfo)
	if err != nil {
		log.Errorf("json marshal container info error %v", err)
		return
	}

	dirURL := fmt.Sprintf(container.DefaultInfoLocation, containerName)
	configFilePath := dirURL + container.ConfigName
	if err := ioutil.WriteFile(configFilePath, newContentBytes, 0622); err != nil {
		log.Errorf("write file %s error %v", configFilePath, err)
	}
}

func removeContainer(containerName string) {
	containerInfo, err := container.GetContainerInfoByName(containerName)
	if err != nil {
		log.Errorf("get container %s info err %v", containerName, err)
		return
	}

	if containerInfo.Status != container.STOP {
		log.Errorf("could't remove running container")
		return
	}

	dirURL := fmt.Sprintf(container.DefaultInfoLocation, containerName)
	if err := os.RemoveAll(dirURL); err != nil {
		log.Errorf("remove file %s error %v", dirURL, err)
		return
	}
	container.DeleteWorkSpace(containerInfo.Volume, containerName)
}